package com.nulp.psycho.web.servlet.interpretation;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.nulp.psycho.db.model.Interpretation;
import com.nulp.psycho.db.model.Result;
import com.nulp.psycho.db.model.User;
import com.nulp.psycho.db.service.InterpretationService;
import com.nulp.psycho.db.service.ResultService;


public class MotivationTestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int motivation = 0;
	
		@SuppressWarnings("unchecked")
		List<String> ans =  (List<String>) request.getAttribute("answers");
		int testId = Integer.parseInt(request.getParameter("testIdid"));
		User user = (User) request.getSession(true).getAttribute("user");
		
		for (int i = 0; i < ans.size(); i++) {
			
			if((i==1)||(i==5)||(i==6)||(i==7)||(i==13)||(i==15)||(i==17)||(i==18)||(i==20)||(i==21)){
				if(ans.get(i).equals("Так")){
					motivation++;
				}
			}
			
			if ((i==0)||(i==2)||(i==3)||(i==4)||(i==8)||(i==10)||(i==11)||(i==12)||(i==14)||(i==16)||(i==19)) {
				if(ans.get(i).equals("Ні")){
					motivation++;
				}
			}
		}
		
		ResultService service = new ResultService();
		Result res = new Result();
		res.setParam("мотивація");
		res.setValue(motivation);
		res.setTestId(testId);
		res.setUserId(user.getId());		
		service.create(res);
		
		
		Interpretation interpretation = new Interpretation();
		interpretation = new InterpretationService().getInterpretationByValue("мотивація", motivation);
		request.setAttribute("motivationExp", interpretation.getExplanation());
		request.setAttribute("motivationText", interpretation.getText());
		
		
		request.setAttribute("motiv", motivation);
		request.getRequestDispatcher("WEB-INF/pages/results/motivationResult.jsp").forward(request, response);
		
	}

}
